/*
 * @Author: lg
 * @Date: 2024-05-21 09:06:15
 * @LastEditors: lg
 * @LastEditTime: 2024-05-23 09:56:38
 * @Description:
 * @FilePath: \bi-main\src\ajax\index.js
 */
import axios from 'axios';
import { biMessage } from '@/hooks/use-message.js';
const { VITE_APP_API } = import.meta.env;

const TIME_OUT = 30 * 1000;

const options = {
  baseURL: VITE_APP_API,
  // baseURL: 'http://192.168.20.154:5055',
  withCredentials: false,
  timeout: TIME_OUT,
  headers: {
    'Access-Control-Allow-Origin': '*'
  }
};

const MESSAGE_NOTICE = {
  503: '服务器内部异常!',
  401: '访问凭证无效，请重新登录授权!',
  403: '访问凭证无效，请重新登录授权!'
};

class HttpRequest {
  constructor(options) {
    this.instance = axios.create(options);
    // this.instance.CancelToken = axios.CancelToken;
    this.addRequestInterceptor(options);
    this.addResponseInterceptor(options);
  }
  //请求拦截
  addRequestInterceptor() {
    this.instance.interceptors.request.use(
      (config) => {
        // config.headers.token = JSON.parse(window.sessionStorage.getItem('vuex'))?.user?.token || ''
        config.headers.token = '';
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  }

  //相应拦截
  addResponseInterceptor() {
    this.instance.interceptors.response.use(
      (response) => {
        //返回数据是json格式处理函数
        function jsonHandler(response) {
          const { code } = response.data;
          const res = response.data;
          if (code === 200) {
            return response.data;
          } else if (code === 400 || code === 401 || code === 403) {
            biMessage('error', res.message || MESSAGE_NOTICE[code]);
            //如果返回码为需要登录, 清除token,跳转到登录页
            setTimeout(() => {
              // window.sessionStorage.removeItem('vuex');
              // let url = window.location.href;
              // window.location.href = url?.split('#')?.[0];
            }, 500);
            return Promise.reject(res);
          } else {
            const message = res.args?.[0] || res.message;
            biMessage('error', message || 'Error');
            return Promise.reject(res);
          }
        }

        if (response.status === 200) {
          //返回的数据不是对象
          if (
            Object.prototype.toString.call(response.data) !== '[object Object]'
          ) {
            return response;
          }
          return jsonHandler(response);
        } else {
          biMessage('error', response.statusText || 'Error');
          return Promise.reject(response);
        }
      },
      (error) => {
        biMessage('error');
        return Promise.reject(error);
      }
    );
  }
}
const { instance: ajax } = new HttpRequest(options);
export default ajax;
